/**
 * Copyright (c) 2011-2012 Nokia Corporation.
 */

// Constants
var MapsViewElementID = "mapContainer";
var InfoTextElementID = "informationText";
var InfoNoteElementID = "informationNote";
var InfoContainerElementID = "infoContainer";

var DefaultLatitude = 52.531;
var DefaultLongitude = 13.385;

// Change the following constant value to setStaticMap if you want to use
// a static map instead of the pannable map.
var SetMapFunction = setPannableMap;
//var SetMapFunction = setStaticMap;

// Position options for Geolocation API
var positionOptions = {
    enableHighAccuracy: false, // Low accuracy is sufficient by default
    timeout: 30000, // 30 seconds
    maximumAge: 0 // Don't accept cached location
    }

// For pannable map
var map;
var marker;
var lastPosition = [ DefaultLatitude, DefaultLongitude ];


/**
 * Called on startup.
 */
function init()
{
    loadPannableMap();
    getPosition(SetMapFunction);
    
    // Example of the calling QML side from HTML's javascript
    window.qml.callQmlMethod();
    window.qml.callQmlMethodWithParam(1);
}

/**
 * Sets the information text in the HTML context.
 *
 * @param text The text to set.
 */
function setInformationText(text)
{
    var informationNoteElement = document.getElementById(InfoNoteElementID);
    informationNoteElement.style.display='block';

    var informationTextElement = document.getElementById(InfoTextElementID);
    informationTextElement.innerHTML = text;
}

/**
 * Timer for hiding info text
 */
function hideInformationText()
{
    var timer = setTimeout("doHideInformationText()",3000);
}

/**
 * Hide info text
 */
function doHideInformationText()
{
    var informationNoteElement = document.getElementById(InfoNoteElementID);
    informationNoteElement.style.display = 'none';
}

/**
 * Show info
 */
function showInfo()
{
    var informationContainerElement = document.getElementById(InfoContainerElementID);
    informationContainerElement.style.display = 'block';
}

/**
 * Close info
 */
function closeInfo()
{
    var informationContainerElement = document.getElementById(InfoContainerElementID);
    informationContainerElement.style.display = 'none';
}

/**
 * Tries to get the current position of the user using the Geolocation API.
 *
 * @param setMapFunction The function used for setting the map.
 */
function getPosition(setMapFunction)
{
    if (navigator.geolocation) {
        setInformationText("Retrieving location...");
        navigator.geolocation.getCurrentPosition(setMapFunction,
                                                 onError,
                                                 positionOptions);
                                                 
    }
    else {
        setInformationText("No Geolocation API available!");

        setMapFunction({ coords: {
            latitude: DefaultLatitude,
            longitude: DefaultLongitude }});
    }
}

/**
 * Loads the map according to the given position.
 *
 * @param position The position received from the Geolocation API.
 */
function setStaticMap(position)
{
    hideInformationText();
    
    setInformationText(position.coords.latitude);
    
    // Get the maps view element.
    var mapsViewElement = document.getElementById(MapsViewElementID);

    // Load the map and set it as the background image of the maps view
    // element.
    var url = new StaticMap({
        center: { lat: position.coords.latitude,
                  lon: position.coords.longitude },
        zoom: 12,
        size: { width: document.width, height: document.height }
    }).getCSSUrl();

    mapsViewElement.style.backgroundImage = url;
}


/**
 * Creates a pannable map.
 */
function loadPannableMap()
{
    setInformationText("Loading Nokia Maps...");

    map = new nokia.maps.map.Display(
        document.getElementById(MapsViewElementID), {
            components: [ new nokia.maps.map.component.Behavior()],
            'zoomLevel': 12, // Zoom level for the map
            'center': [DefaultLatitude, DefaultLongitude] // Center coordinates
        }
    );
}


/**
 * Centers the map on the given position and add a marker.
 *
 * @param position The position received from the Geolocation API.
 */
function setPannableMap(position)
{
    hideInformationText();
    
    // Store the position.
    lastPosition = position.coords;

    // Center the map.
    map.setCenter( [ position.coords.latitude, position.coords.longitude ] );

    // Create and add the marker.
    marker = new nokia.maps.map.Marker(
                [position.coords.latitude, position.coords.longitude],
                {
                    text: "Me",
                    draggable: false
                });

    // Uncomment the following to use a custom marker.
    //marker.set("icon", "images/marker.png");

    map.objects.clear();
    
    map.objects.add(marker);
}


/**
 * Callback for handling errors. Displays the error message in the HTML
 * context.
 *
 * @param error The occured error.
 */
function onError(error)
{
    setInformationText("Error: " + error.message);
    alert("Error: " + error.message);
}


/**
 * Sets the accuracy according to the given argument. Tries to update the
 * position automatically.
 *
 * @param accuracy Should be "high" or "low" depending on the desired accuracy.
 */
function setAccuracy(accuracy)
{
    if (accuracy == "high") {
        setInformationText("Accuracy set: high");
        positionOptions.enableHighAccuracy = false;
    }
    else {
        setInformationText("Accuracy set: low");
        positionOptions.enableHighAccuracy = true;
    }

    getPosition(SetMapFunction);
}


/**
 * Centers the map. This has an effect only if the pannable map is in use.
 */
function centerMap()
{
    if (map) {
        map.setCenter(lastPosition);
    }
}


/**
 * Updates the position.
 */
function update()
{
    setInformationText("Update...");
    getPosition(SetMapFunction);
}


// End of file.
